package cn.techjc.action;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.apache.tomcat.jni.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.techjc.domain.Users;
import cn.techjc.domain.UsersVoteInfo;
import cn.techjc.service.VotedService;
import cn.techjc.utils.IPer;

@Controller
public class VotedAction {
	private static Logger log = Logger.getLogger(VotedAction.class);

	@Autowired
	public VotedService votedService;

	@Autowired
	public RedisTemplate<String, String> redisTemplate;

	@RequestMapping("/userList")
	public String userList(HttpServletRequest request, HttpSession session,
			Model model) {
		
		List<Map<String, String>> results = votedService.getUsersNumFromRedis();
		model.addAttribute("results", results);
		return "userList";
	}

	@ResponseBody
	@RequestMapping("/voteAdd")
	public Map<String, Object> voteAdd(HttpServletRequest request,
			HttpServletResponse response, HttpSession session, String userId,
			String userName) {
		Map<String, Object> params = new HashMap<String, Object>();
		UsersVoteInfo voteInfo = new UsersVoteInfo();
		params.put("message", "ok");
		int countLimit = votedService.voteLimit(IPer
				.getClientIpAddress(request));
		Users user = votedService.selectIdByName(userName);
		if (countLimit < 5) {
			String dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:sss")
					.format(new Date());
			voteInfo.setUserId(user.getId());
			voteInfo.setIp(IPer.getClientIpAddress(request));
			voteInfo.setSessionId(session.getId());
			voteInfo.setVoteTime(dateFormat);
			votedService.voteAdd(voteInfo);
			votedService.setUsersNumToRedis(userName);
		} else {
			params.put("message", "no");
		}
		return params;
	}
}
